<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务，帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\common\model;

use app\common\enum\Setting as SettingEnum;
use app\common\library\express\Kuaidi100Order;
use app\common\library\helper;
use app\common\model\store\Setting as SettingModel;
use app\store\model\Express as ExpressModel;
use cores\BaseModel;
use app\common\model\Region as RegionModel;

/**
 * 售后单退货地址模型
 * Class OrderRefundAddress
 * @package app\common\model
 */
class OrderRefundAddress extends BaseModel
{
    // 定义表名
    protected $name = 'order_refund_address';

    // 定义主键
    protected $pk = 'id';

    protected $updateTime = false;

    /**
     * 追加字段
     * @var array
     */
    protected $append = ['region'];

    /**
     * 获取器：地区名称
     * @param $value
     * @param $data
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getRegionAttr($value, $data)
    {
        return [
            'province' => RegionModel::getNameById($data['province_id']),
            'city'     => RegionModel::getNameById($data['city_id']),
            'region'   => RegionModel::getNameById($data['region_id'])
        ];
    }

    //向快递100提交快递订单
    public function csentOrder($data)
    {
        // 获取物流信息
        $model = ExpressModel::detail($data['expressId']);
        $param = array(
            'kuaidicom'        => $model['kuaidi100_code'],              // 快递公司的编码
            'recManName'       => $data['recManName'],             // 收件人姓名
            'recManMobile'     => $data['recManMobile'],           // 收件人手机号
            'recManPrintAddr'  => $data['recManPrintAddr'],        // 收件人所在完整地址
            'sendManName'      => $data['sendManName'],            // 寄件人姓名
            'sendManMobile'    => $data['sendManMobile'],          // 寄件人的手机号
            'sendManPrintAddr' => $data['sendManPrintAddr'],       // 寄件人所在的完整地址
            'callBackUrl'      => app()->config->get('app.callback_url') . '/index.php?s=/api/callback/csentOrder',// callBackUrl订单信息回调，默认仅支持http
            'cargo'            => $data['cargo'],                  // 物品名称
            'payment'          => 'SHIPPER',         // 支付方式，SHIPPER: 寄付（默认）。不支持到付
            //'weight' => '0.5',              // 物品总重量KG，不需带单位
            'dayType'          => '今天',            // 预约日期，例如：今天/明天/后天
            'pickupStartTime'  => '',        // 预约起始时间（HH:mm），例如：09:00
            'pickupEndTime'    => '',          // 预约截止时间（HH:mm），例如：10:00
            'salt'             => 'bangnuo',                 // 签名用随机字符串
            'passwordSigning'  => 'N',       // 是否口令签收，Y：需要 N: 不需要
            'op'               => '1',                    // 是否开启订阅功能 0：不开启(默认) 1：开启
            'pollCallBackUrl'  => app()->config->get('app.callback_url') . '/index.php?s=/api/callback/poll',      // 如果op设置为1时，pollCallBackUrl必须填入，用于跟踪回调
            'resultv2'         => '0'               // 此字段表示开通行政区域解析或地图轨迹功能
        );
        // 获取快递100配置项
        $config = $this->getKuaidi100Config();
        // 实例化快递100类
        $Kuaidi100 = new Kuaidi100Order($config);
        // 用户下单
        $order_result = $Kuaidi100->orderProcessing($param, 'cOrder');
        // 记录日志
        log_record(['name' => '上门取件下单', 'data' => $order_result]);
        $result = helper::jsonDecode($order_result);
        // 记录错误信息
        if ($result['returnCode'] != 200 || empty($result['data'])) {
            $this->error = $result['message'] ?? '下单失败';
            return false;
        }
        $task_order_id = '';
        if ($result['data']['orderId'] && $result['data']['taskId']) {
            $task_order_id = $result['data']['orderId'] . ',' . $result['data']['taskId'];
        }
        //更新下单信息
        $shippingAddress = ['name' => $data['sendManName'], 'phone' => $data['sendManMobile'], 'sendManPrintAddr' => $data['sendManPrintAddr']];
        $updateData      = ['type'            => 1, 'shipping_address' => json_encode($shippingAddress),
                            'callback_result' => $order_result, 'task_order_id' => $task_order_id];
        return $this->where(['order_refund_id' => $data['order_refund_id']])->update($updateData);
    }

    /**
     * 取消寄件
     * @param $order_data
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function corderapi($order_data)
    {
        if (isset($order_data['address']['callback_result']) && !empty($order_data['address']['callback_result'])) {
            $callback_result = $order_data['address']['callback_result'];
            //订单状态11:"揽货失败";12:"已退回';99:"订单已取消”;201:"出单失败';610:'下单失败';
            $status = [11, 12, 99, 201, 610];
            if (isset($callback_result['status']) && in_array($callback_result['status'], $status)) {
                $this->where(['order_refund_id' => $order_data['order_refund_id']])->update(['type' => 0]);
                return true;
            }
        }
        $task_order = ['', ''];
        if ($order_data['address']['task_order_id']) {
            $task_order = explode(',', $order_data['address']['task_order_id']);
        }
        if (empty($task_order[1]) && empty($task_order[0])) {
            $this->error = $result['message'] ?? '取消失败';
            return false;
        }
        $param = array(
            'taskId'    => $task_order[1],                  // 任务ID
            'orderId'   => $task_order[0],                 // 订单ID
            'cancelMsg' => '暂时不寄件了'                // 取消原因，例：暂时不寄件了
        );
        // 获取快递100配置项
        $config = $this->getKuaidi100Config();
        // 实例化快递100类
        $Kuaidi100 = new Kuaidi100Order($config);
        // 用户下单
        $order_result = $Kuaidi100->orderProcessing($param, 'cancel');
        log_record(['name' => '取消上门取件', 'data' => $order_result]);
        $result = helper::jsonDecode($order_result);
        // 记录错误信息
        if ($result['returnCode'] == 200 && $result['result']) {
            $this->where(['order_refund_id' => $order_data['order_refund_id']])->update(['type' => 0]);
            return true;
        }
        $this->error = $result['message'] ?? '取消失败';
        return false;
    }

    //向快递100提交收件地址获取快递价格(收费项目)
    /*public function getKuaiDiPrice($data)
    {
        //顺丰速运需要传业务类型为"顺丰标快"，其他快递公司可不传
        $serviceType = null;
        if ($data['expressId'] == '10001') {
            $serviceType = '顺丰标快';
        }
        // 获取物流信息
        $model = ExpressModel::detail($data['expressId']);
        $param = array(
            'kuaidicom'        => $model['kuaidi100_code'],         // 快递公司的编码
            'sendManPrintAddr' => $data['sendManPrintAddr'],         // 出发地地址，最小颗粒到市级
            'recManPrintAddr'  => $data['recManPrintAddr'],        // 目的地地址，最小颗粒到市级
            'weight'           => '1',                              // 物品总重量KG，不需带单位
            'serviceType'      => $serviceType                      // 业务类型
        );
        // 获取快递100配置项
        $config = $this->getKuaidi100Config();
        // 实例化快递100类
        $Kuaidi100 = new Kuaidi100Order($config);
        // 用户下单
        $price_result = $Kuaidi100->orderProcessing($param, 'price');
        // 记录日志
        log_record(['name' => '获取寄快递价格', 'data' => $price_result]);
        $result = helper::jsonDecode($price_result);
        // 记录错误信息
        if ($result['returnCode'] != 200 || empty($result['data'])) {
            $this->error = $result['message'] ?? '价格获取失败';
            return false;
        }
    }*/

    /**
     * 获取快递100配置项
     * @return mixed
     * @throws \app\common\exception\BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private function getKuaidi100Config()
    {
        // 实例化快递100类
        $config                        = SettingModel::getItem(SettingEnum::DELIVERY);
        $config['kuaidi100']['secret'] = '978cd3202c6c4cbdb90750e4536609a1';
        if (empty($config['kuaidi100']['customer']) || empty($config['kuaidi100']['key'])) {
            throwError('请先到后台-设置-配送方式 补充物流查询API配置');
        }
        return $config['kuaidi100'];
    }

}
